$(function() {
	//点击切换
	var txt = "",
		ul = $("#wodekecheng").find("ul"),
		div = $("#wodekecheng").find(".jiazai"),
		html = "";
	html = ul.eq(0);
	//kecheng(1, html);
	$("#wodekecheng .peixun").find("a").click(function() {
		txt = $(this).text()
		if(txt == "已约课程") {
			ul.eq(0).show();
			ul.eq(1).hide();
			div.hide();
			html = ul.eq(0);
			kecheng(1, html);

		} else {
			ul.eq(1).show();
			ul.eq(0).hide();
			div.show();
			html = ul.eq(1);
			kecheng(2, html);
		}
		$(this).addClass("intro");
		$(this).siblings().removeClass("intro");
	})

	//以约课程
	function kecheng(type, wenbeng) {
		var txt = "",shijian = "",h5 = "已开课";
		wenbeng.empty();
		new Ajax("/yiyuekecheng").keyvalue("myid", RssUser.Data.myid).keyvalue("type", type).getJson(function(json) {
			JSON.stringify(json.sort(function(x, y) {
				var t1, t2;
				t1 = shi(x["start"]);
				t2 = shi(y["start"]);
				var x = x["time"] + t1,
					y = y["time"] + t2;
				if(x == y) {
					return 0;
				}
				return x - y;
			}))
			if(type == "1") {
				h5 = "取消预约";
			}
			$.each(json, function(key, val) {
				shijian = joint(val["start"]);
				var z = new Date(val["time"] * 1000).toLocaleString().substr(5, 5);
				txt += "<li><h1>" + shijian + "<span>" + z + "</span></h1><h2>" + val["name"] + "</h2><h3>" + val["teachername"] + "</h3><h5 time='"+val["time"]+"' dingdan ='"+val["xianxiapeixunid"]+"' card='"+val["cardid"]+"' start='"+val["start"]+"'>"+ h5 +"</h5></li>"
			});
			wenbeng.html(txt);
			//取消预约
			var cencel = ul.eq(0).find("h5");
			cencel.click(function() {
				
				if($(this).text() == "取消预约") {
				
					var myDate = new Date();
					var time =parseInt(myDate.getTime() / 1000);
					var coursetime = $(this).attr("time");
					var coursestart = $(this).attr("start");
					var dingdan = $(this).attr("dingdan");
					var card = $(this).attr("card");					
					coursestart = shi(coursestart);
					coursestart = parseInt(coursestart) +parseInt(coursetime); //课程时间
					if(coursestart - time > 43200) {	
						new Ajax("/cancelcourse").keyvalue("myid", RssUser.Data.myid).keyvalue("xianxiapeixunid", dingdan).keyvalue("card",card).get(function(json) {})
							$(this).text("已取消").css({
								'background': '#ccc'
							});						
					}else{
						alert("您好距离开课不足12小时你可以以请假的方式取消预约");
					}
				}
			})
		})
	}

	//字符串拼接
	function joint(join) {
		var le = join.length;
		var str;
		if(le == 3) {
			str = join.substring(0, 1) + ":";
			str = str + join.substring(1, 3);
		} else {
			str = join.substring(0, 2) + ":";
			str = str + join.substring(2, 4);
		}
		return str;
	}
	//计算开课时间转化为秒
	function shi(join) {
		var le = join.length;
		var shi, feng, t;
		if(le == 3) {
			shi = join.substring(0, 1) * 3600;
			feng = join.substring(1, 3) * 60;
			t = shi + feng;
		} else {
			shi = join.substring(0, 2) * 3600;
			feng = join.substring(2, 4) * 60;
			t = shi + feng;
		}
		return t;
	}
	//点击加载全部
	$("#wodekecheng").find(".jiazai").click(function() {
		html = ul.eq(1);
		kecheng(3, html);
	})

})